@file:OptIn(ExperimentalMaterial3Api::class)

package com.zykj.evaluation.ui.home

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.zykj.evaluation.R
import com.zykj.evaluation.extend.ProvideLtr
import com.zykj.evaluation.extend.ProvideRtl
import com.zykj.evaluation.model.DrawerContent
import com.zykj.evaluation.model.TodoTask
import com.zykj.evaluation.ui.ActionButton
import com.zykj.evaluation.ui.Detail
import com.zykj.evaluation.ui.TabList
import com.zykj.evaluation.ui.theme.PrimaryColorLight
import com.zykj.evaluation.viewmodel.HomeAction
import com.zykj.evaluation.viewmodel.HomeViewModel
import kotlinx.coroutines.launch

@Composable
fun Home(homeViewModel: HomeViewModel, onStartAnswer: (TodoTask) -> Unit) {
    val viewState by homeViewModel.homeViewState

    val coroutineScope = rememberCoroutineScope()
    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    val topBarHeight = 64.dp

    val tabList = viewState.tabList
    val detailLazyListStates: Map<Int, LazyGridState> = tabList.associate { post ->
        key(post.label) {
            post.label to rememberLazyGridState()
        }
    }

    ProvideRtl {
        ModalNavigationDrawer(
            drawerState = drawerState,
            gesturesEnabled = drawerState.isOpen,
            drawerShape = RoundedCornerShape(bottomEnd = 16.dp),
            drawerContent = {
                ProvideLtr {
                    HomeFilter(
                        homeViewModel = homeViewModel,
                        drawerState = drawerState,
                        topBarHeight = topBarHeight,
                        closeDrawer = {
                            coroutineScope.launch {
                                drawerState.close()
                            }
                        }) {
                    }
                }
            }) {

            ProvideLtr {
                Scaffold(topBar = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(topBarHeight)
                            .background(MaterialTheme.colorScheme.primaryContainer)
                            .statusBarsPadding(),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = stringResource(id = R.string.my_evaluation),
                            style = MaterialTheme.typography.titleMedium.copy(
                                color = Color.White
                            )
                        )
                    }
                }, content = { contentPadding ->
                    Row(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(contentPadding)
                    ) {
                        TabList(
                            tabList = tabList,
                            modifier = Modifier
                                .width(81.dp)
                                .fillMaxHeight()
                                .background(Color.White),
                            current = viewState.selectedTab
                        ) {
                            homeViewModel.dispatch(HomeAction.TabSwitch(it))
                        }
                        Column {
                            SearchBar(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .background(color = Color.White)
                                    .height(38.dp),
                                keyboardActions = {
                                    homeViewModel.dispatch(HomeAction.Search(this))
                                }
                            ) {
                                coroutineScope.launch {
                                    drawerState.open()
                                }
                            }
//                            Crossfade(targetState = viewState.selectedTab) { tab ->
//                                val detailLazyListState by derivedStateOf {
//                                    detailLazyListStates.getValue(tab.label)
//                                }
//                                key(viewState.selectedTab.label) {
                            Detail(
                                modifier = Modifier.fillMaxSize(),
                                contentPadding = PaddingValues(10.dp),
                                horizontalSpace = 5.dp,
                                verticalSpace = 10.dp,
                                todoEvaluationList = viewState.pageData,
                                onStartAnswer = onStartAnswer
                            )
//                                }
//                            }
                        }
                    }
                })
            }
        }
    }
}

@Composable
fun HomeFilter(
    homeViewModel: HomeViewModel,
    drawerState: DrawerState,
    closeDrawer: () -> Unit,
    topBarHeight: Dp,
    filterResult: () -> Unit
) {
    val filterData = homeViewModel.homeViewState.value.filterData
    val filterSelection = homeViewModel.homeViewState.value.filterSelection
    ConstraintLayout(
        modifier = Modifier
            .fillMaxSize()
            .background(color = MaterialTheme.colorScheme.background)
    ) {
        val (topSpacer, subject, review, time, action) = createRefs()
        BackHandler(enabled = drawerState.isOpen, onBack = {
            closeDrawer.invoke()
        })
        Spacer(
            modifier = Modifier
                .height(topBarHeight)
                .windowInsetsTopHeight(WindowInsets.statusBars)
                .constrainAs(ref = topSpacer) {
                    top.linkTo(parent.top)
                }
        )
        DrawerItem(
            contentPadding = PaddingValues(10.dp),
            horizontalSpace = 5.dp,
            verticalSpace = 5.dp,
            headerText = "科目",
            modifier = Modifier.constrainAs(ref = subject) {
                top.linkTo(topSpacer.bottom)
                bottom.linkTo(review.top)
            }
        ) {
            itemsIndexed(filterData.subjectList) { index, item ->
                GridItem(drawerContent = item, checked = filterSelection.subjectIndex == index) {
                    homeViewModel.dispatch(HomeAction.FilterSelect(item, index))
                }
            }
        }
        DrawerItem(
            contentPadding = PaddingValues(10.dp),
            horizontalSpace = 5.dp,
            verticalSpace = 5.dp,
            headerText = "批阅方式",
            modifier = Modifier.constrainAs(ref = review) {
                top.linkTo(subject.bottom)
                bottom.linkTo(time.top)
            }
        ) {
            itemsIndexed(filterData.reviewList) { index, item ->
                GridItem(drawerContent = item, checked = filterSelection.reviewIndex == index) {
                    homeViewModel.dispatch(HomeAction.FilterSelect(item, index))
                }
            }
        }
        DrawerItem(
            contentPadding = PaddingValues(10.dp),
            horizontalSpace = 5.dp,
            verticalSpace = 5.dp,
            headerText = "测评开始时间",
            modifier = Modifier.constrainAs(ref = time) {
                top.linkTo(review.bottom)
            }
        ) {
            itemsIndexed(filterData.timeList) { index, item ->
                GridItem(drawerContent = item, checked = filterSelection.timeIndex == index) {
                    homeViewModel.dispatch(HomeAction.FilterSelect(item, index))
                }
            }
        }

        Row(modifier = Modifier
            .constrainAs(action) {
                bottom.linkTo(parent.bottom)
            }
            .fillMaxWidth()
            .padding(bottom = 20.dp),
            horizontalArrangement = Arrangement.Center) {
            ActionButton(
                label = "重置",
                fontColor = Color.Gray,
                containerColor = Color(0xFFE6E6E6),
                modifier = Modifier.size(width = 80.dp, height = 40.dp),
                shape = RoundedCornerShape(20.dp)
            ) {
                homeViewModel.dispatch(HomeAction.FilterReset)
            }
            Spacer(modifier = Modifier.width(20.dp))
            ActionButton(
                label = "确定",
                modifier = Modifier.size(width = 80.dp, height = 40.dp),
                shape = RoundedCornerShape(20.dp)
            ) {

            }
        }

    }
}

@Composable
fun DrawerItem(
    headerText: String,
    modifier: Modifier = Modifier,
    contentPadding: PaddingValues,
    horizontalSpace: Dp,
    verticalSpace: Dp,
    content: LazyGridScope.() -> Unit
) {
    Column(modifier = modifier) {
        Text(
            text = headerText,
            modifier = Modifier.padding(
                start = contentPadding.calculateStartPadding(LayoutDirection.Ltr)
            ),
            style = MaterialTheme.typography.bodyMedium
        )
        LazyVerticalGrid(
            columns = GridCells.Fixed(5),
            verticalArrangement = Arrangement.spacedBy(verticalSpace),
            horizontalArrangement = Arrangement.spacedBy(horizontalSpace),
            contentPadding = contentPadding,
        ) {
            content()
        }
    }
}

@Composable
private fun GridItem(
    drawerContent: DrawerContent,
    checked: Boolean,
    action: (
        drawerContent: DrawerContent
    ) -> Unit
) {
    Button(
        onClick = { action(drawerContent) },
        shape = RoundedCornerShape(8.dp),
        colors = ButtonDefaults.textButtonColors(containerColor = if (checked) Color(0xFFBFD9F7) else Color.White),
        modifier = Modifier
            .height(30.dp),
        contentPadding = PaddingValues(0.dp)
    ) {
        Text(
            text = drawerContent.content(),
            maxLines = 1,
            style = MaterialTheme.typography.labelSmall.copy(
                color = if (checked) PrimaryColorLight else Color(
                    0xFF4F4F4F
                )
            ),
            textAlign = TextAlign.Start,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier
                .padding(horizontal = 5.dp)
        )
    }
}

@Composable
fun SearchBar(
    modifier: Modifier = Modifier,
    keyboardActions: String.() -> Unit,
    filterClick: () -> Unit
) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = modifier.padding(start = 10.dp, end = 10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        CustomTextField(
            textFieldStyle = TextStyle(
                color = colorResource(id = R.color.teal_200),
                fontSize = 12.sp
            ),
            hintTextStyle = TextStyle(
                color = colorResource(R.color.purple_200),
                fontSize = 12.sp
            ),
            hint = "请输入关键词",
            leadingIcon = {
                Image(
                    painter = rememberVectorPainter(Icons.Outlined.Search),
                    contentDescription = null,
                    Modifier.size(15.dp, 15.dp)
                )
            },
            modifier = Modifier.width(200.dp),
            keyboardActions = keyboardActions
        )
        Image(
            contentDescription = null,
            imageVector = ImageVector.vectorResource(id = R.drawable.icon_bar_filter),
            modifier = Modifier
                .size(35.dp, 35.dp)
                .clickable {
                    filterClick.invoke()
                }
                .padding(8.dp)
        )
    }
}

